package com.headwind.logistics.common.shiro;

import com.headwind.logistics.common.pojo.Employee;
import com.headwind.logistics.common.pojo.Menu;
import com.headwind.logistics.permission.service.intl.EmployeeServiceIntl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    @Lazy //此注解防止业务逻辑层实现类事务失效  防止service对象被ShiroFilterFactoryBean提前初始化(导致事务失效)
    private EmployeeServiceIntl employeeServiceIntl;

    /**
     * 用于获取登录成功后的角色、权限等信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权执行");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取subject里的员工对象
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        //获取权限字符串
        List<Menu> menuList = employeeServiceIntl.queryMenuPermsByEmpId(employee.getEmployeeId());
        //给用户进行授权权限
        for (Menu menu : menuList) {
            if (menu.getPerms() !=null){
                info.addStringPermission(menu.getPerms());
            }

        }

        return info;
    }

    /**
     * 验证当前登录的Subject
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        //拿到账号（username）
        String username = (String) usernamePasswordToken.getUsername();

        String empPassword = new String(usernamePasswordToken.getPassword());


        Employee emp = new Employee();
        emp.setEmployeeNo(username);
        emp.setPassword(empPassword);

        Employee employee = employeeServiceIntl.adminLogin(emp);
        if (employee==null){
            return null;
        }


        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee,employee.getPassword(),getName());
        return info;
    }
}
